<template>
  <a-layout>
    <a-layout-content :style="{ background: '#fff', padding: '24px', margin: 0, minHeight: '280px' }">
      <a-form layout="inline" :model="param" style="margin-bottom: 15px;">
        <a-form-item>
          <a-input v-model:value="param.name" placeholder="名称"/>
        </a-form-item>
        <a-form-item>
          <a-button type="primary" @click="search">查询</a-button>
        </a-form-item>
        <a-form-item>
          <a-button type="primary" @click="add">新增</a-button>
        </a-form-item>
      </a-form>
      <a-table
          :columns="columns"
          :row-key="record=>record.id"
          :data-source="ebooks"
          :pagination="pagination"
          :loading="loading"
          @change="handleTableChange"
      >
        <template #bodyCell="{column,text,record}">
          <template v-if="column.dataIndex === 'cover'">
            <img v-if="text" :src="text" alt="封面图片" style="width: 35px;height: 35px;">
            <span v-else>暂无封面</span>
          </template>
          <template v-if="column.dataIndex === 'category'">
            <span v-if="record.category1Name && record.category2Name">
            {{ record.category1Name }} / {{ record.category2Name }}
            </span>
            <span v-else>没有分类</span>
          </template>
          <template v-if="column.dataIndex === 'action'">
            <a-space size="small">
              <a-button type="primary" @click="edit(record.id)" shape="round">编辑</a-button>
              <a-button type="primary" danger shape="round" @click="del(record.id)">删除</a-button>
            </a-space>
          </template>
        </template>
      </a-table>
    </a-layout-content>
  </a-layout>
  <a-modal v-model:visible="visible"
           title="电子书管理"
           :confirm-loading="confirmLoading"
           @ok="handleOk">
    <a-form :model="formData" :label-col="labelCol" :wrapper-col="wrapperCol">
      <a-form-item label="封面">
        <a-image v-if="formData.cover" :src="formData.cover"/>
        <span v-else>暂无封面</span>
      </a-form-item>
      <a-form-item label="名称" name="name">
        <a-input v-model:value="formData.name"/>
      </a-form-item>
      <a-form-item label="分类">
        <a-cascader v-model:value="categoryIds" :options="options"
                    :field-names="{label:'name',value:'id',children:'children'}"/>
      </a-form-item>
      <a-form-item label="描述">
        <a-textarea v-model:value="formData.description" auto-size/>
      </a-form-item>
    </a-form>
  </a-modal>
</template>
<script setup lang="ts">
import {onMounted, ref} from "vue";
import request from '@/util/request';
import {message, Modal} from "ant-design-vue";
import Tool from "@/util/toTree";
/*级联选择器*/
const categoryIds = ref();
const options = ref();
const getCategories = () => {
  request.get('/category/list').then(res => {
    const data = res.data;
    options.value = Tool.array2Tree(data, 0);
  })
}
/*查询的名字*/
const param = ref({
  name: ''
});
/*查询操作*/
const search = () => {
  handleQuery({
    current: pagination.value.current,
    pageSize: pagination.value.pageSize,
    name: param.value.name
  })
}
/*编辑还是新增*/
const type = ref();
/*删除*/
const del = (id: number) => {
  console.log("要删除的id", id)
  Modal.confirm({
    title: '确定要删除吗?',
    content: '电子书',
    okText: '确定',
    okType: 'danger',
    cancelText: '取消',
    onOk() {
      request.delete(`/ebook/${id}`).then(() => {
        message.success("删除成功！")
        handleQuery({
          current: 1,
          pageSize: pagination.value.pageSize
        });
      })
    },
    onCancel() {
      message.info("取消删除")
    },
  });
}
/*新增*/
const add = () => {
  visible.value = true
  formData.value = {category1Id: "", category2Id: "", cover: "", description: "", id: "", name: ""}
  type.value = 'add'
}
/*编辑*/
const edit = (id: number) => {
  visible.value = true
  request.get(`/ebook/${id}`).then(res => {
    formData.value = res.data
    categoryIds.value = [res.data.category1Id, res.data.category2Id]
  })
  type.value = 'edit'
}
/*表单*/
const visible = ref<boolean>(false);
const confirmLoading = ref<boolean>(false);
const formData = ref({
  id: '',
  cover: '',
  name: '',
  category1Id: '',
  category2Id: '',
  description: ''
});
const labelCol = {style: {width: '150px'}};
const wrapperCol = {span: 14};
const handleOk = () => {
  console.log(type.value)
  confirmLoading.value = true;
  if (type.value === 'edit') {
    formData.value.category1Id = categoryIds.value[0]
    formData.value.category2Id = categoryIds.value[1]
    request.put('/ebook', formData.value).then(() => {
      confirmLoading.value = false;
      visible.value = false;
      message.success('更新成功')
      handleQuery({
        current: pagination.value.current,
        pageSize: pagination.value.pageSize
      });
    }).catch(err => {
      confirmLoading.value = false
      console.log(err)
    })
  } else {
    request.post('/ebook', formData.value).then(() => {
      confirmLoading.value = false;
      visible.value = false;
      message.success('新增成功')
      handleQuery({
        current: pagination.value.current,
        pageSize: pagination.value.pageSize
      });
    }).catch(err => {
      confirmLoading.value = false
      console.log(err)
    })
  }
};

/*电子书*/
let ebooks = ref([])
/*分页*/
let pagination = ref({
  current: 1,
  pageSize: 5,
  total: 0,
  showTotal: (total: number) => `共${total}条数据`,
})
let loading = ref(false)

/*表格列*/
const columns = [
  {
    title: '封面',
    dataIndex: 'cover',
    // slots: {customRender: 'cover'}
  },
  {
    title: '名称',
    dataIndex: 'name'
  },
  {
    title: '分类',
    key: 'category',
    dataIndex: 'category',
  },
  {
    title: '文档数',
    key: 'docCount',
    dataIndex: 'docCount',
  },
  {
    title: '阅读数',
    key: 'viewCount',
    dataIndex: 'viewCount',
  },
  {
    title: '点赞数',
    key: 'voteCount',
    dataIndex: 'voteCount',
  },
  {
    title: 'Action',
    key: 'action',
    dataIndex: 'action',
  }
]
/*数据查询*/
const handleQuery = (params: any) => {
  loading.value = true
  request.get('/ebook/page', {
    params: {
      current: params.current,
      pageSize: params.pageSize,
      name: params.name
    }
  }).then(res => {
    loading.value = false;
    ebooks.value = res.data.records;
    console.log(ebooks.value)
    //  重置分页属性
    pagination.value.total = res.data.total;
    pagination.value.current = params.current;
  }).catch(err => {
    loading.value = false;
    console.log(err)
  })
}

/*表格点击时候触发*/
const handleTableChange = (pagination: any) => {
  handleQuery({
    current: pagination.current,
    pageSize: pagination.pageSize
  });
}


onMounted(() => {
  handleQuery({
    current: pagination.value.current,
    pageSize: pagination.value.pageSize
  });
  getCategories()
})
</script>
<style scoped>
.avatar-uploader > .ant-upload {
  width: 128px;
  height: 128px;
}

.ant-upload-select-picture-card i {
  font-size: 32px;
  color: #999;
}

.ant-upload-select-picture-card .ant-upload-text {
  margin-top: 8px;
  color: #666;
}
</style>